package org.ws.task.repository;

import com.google.common.collect.Maps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.ws.task.model.NodeMetadata;
import org.ws.task.model.TaskStatistics;

import java.util.Map;

/**
 * 任务管理
 */
public class TaskStatisticsRepository {

    private static final TaskStatisticsRepository INSTANCE = new TaskStatisticsRepository();

    public static final TaskStatisticsRepository getInstance(){
        return INSTANCE;
    }
    private TaskStatisticsRepository(){
    }

    private Map<String, TaskStatistics> taskStatisticsMap = Maps.newConcurrentMap();

    public void register(String workerName){
        if(taskStatisticsMap.containsKey(workerName)){
            return;
        }
        taskStatisticsMap.putIfAbsent(workerName,new TaskStatistics(workerName));
    }

    public void register(NodeMetadata nodeMetadata){
        if(taskStatisticsMap.containsKey(nodeMetadata.getId())){
            return;
        }
        taskStatisticsMap.putIfAbsent(nodeMetadata.getId(),new TaskStatistics(nodeMetadata.getId()));
    }

    /**
     * 获取任务总数统计
     * @param workerName
     * @return
     */
    public TaskStatistics getTaskStatistics(String workerName){
        if(!taskStatisticsMap.containsKey(workerName)){
            register(workerName);
        }
        return taskStatisticsMap.get(workerName);
    }

    public TaskStatistics getTaskStatistics(NodeMetadata nodeMetadata){
        if(!taskStatisticsMap.containsKey(nodeMetadata.getId())){
            register(nodeMetadata);
        }
        return taskStatisticsMap.get(nodeMetadata.getId());
    }

}
